<template>
  <div class="relation-map">
    <div class="map-container">
      <!-- 左侧浮动卡片 -->
      <div class="floating-cards">
        <!-- 实体类型卡片 -->
        <div class="entity-type-card">
          <div class="card-header">
            <span class="card-title">实体筛选</span>
          </div>
          <div class="card-content" v-show="!isEntityTypeCardCollapsed">
            <div class="filter-input">
              <a-input-search
                v-model:value="searchText"
                placeholder="输入实体名称搜索"
                @search="handleSearch"
                allowClear
              />
            </div>
          </div>
        </div>

        <!-- 数据查看卡片 -->
        <div class="data-card">
          <div class="card-header">
            <span class="card-title">实体数据</span>
            <a-button type="text" size="small" @click="toggleDataCard">
              <i class="fas" :class="isDataCardCollapsed ? 'fa-chevron-down' : 'fa-chevron-up'"></i>
            </a-button>
          </div>
          <div class="card-content" v-show="!isDataCardCollapsed">
            <div class="data-list">
              <template v-if="selectedEntities.length > 0">
                <div v-for="(entity, index) in selectedEntities" :key="index" class="entity-item">
                  <div class="entity-header">
                    <div class="entity-name">{{ entity.name }}</div>
                  </div>
                  <div class="entity-fields">
                    <div v-for="(value, key) in entity.fields" :key="key" class="field-item">
                      <div class="field-label">{{ key }}</div>
                      <div 
                        v-if="key === 'ID' || key === '依赖接口' || !entity.editingField || entity.editingField !== key" 
                        class="field-value"
                        :class="{ 'editable': key !== 'ID' && key !== '依赖接口' }"
                        @click="key !== 'ID' && key !== '依赖接口' ? startEditField(entity, key) : null"
                      >
                        {{ value }}
                      </div>
                      <a-input 
                        v-else
                        v-model:value="entity.fields[key]" 
                        :placeholder="`请输入${key}`"
                        size="small" 
                        class="field-input"
                        @pressEnter="finishEditField(entity)"
                        @blur="finishEditField(entity)"
                        :id="`field-input-${entity.id}-${key}`"
                      />
                    </div>
                  </div>
                  <div class="entity-actions" v-if="entity.isEdited">
                    <a-button type="primary" size="small" @click="saveEntityChanges(entity, index)">保存</a-button>
                    <a-button size="small" @click="cancelEntityChanges(entity, index)">取消</a-button>
                  </div>
                </div>
              </template>
              <a-empty v-else description="暂无数据" class="empty-data" />
            </div>
          </div>
        </div>
      </div>

      <!-- 关系图谱可视化区域 -->
      <div class="graph-container" ref="graphContainer" :class="{ 'compressed': selectedItem }"></div>
      
      <!-- 工具栏 -->
      <div class="toolbar" :class="{ 'compressed': selectedItem }">
        <div class="tool-group">
          <a-tooltip title="放大">
            <a-button type="text" @click="zoomIn">
              <i class="fas fa-search-plus"></i>
            </a-button>
          </a-tooltip>
          <a-tooltip title="缩小">
            <a-button type="text" @click="zoomOut">
              <i class="fas fa-search-minus"></i>
            </a-button>
          </a-tooltip>
          <a-tooltip title="重置">
            <a-button type="text" @click="resetView">
              <i class="fas fa-sync-alt"></i>
            </a-button>
          </a-tooltip>
        </div>
      </div>

      <!-- 右侧编辑卡片 -->
      <div class="edit-card" :class="{ 'show': selectedItem }">
        <div class="card-header">
          <span class="card-title">{{ selectedItem?.type === 'node' ? '实体编辑' : '关系编辑' }}</span>
          <a-button type="text" size="small" @click="closeEditCard">
            <i class="fas fa-times"></i>
          </a-button>
        </div>
        <div class="card-content">
          <template v-if="selectedItem?.type === 'node'">
            <!-- 实体编辑表单 -->
            <div class="form-label">关联关系</div>
            <div class="related-entities">
              <template v-if="relatedEntities.length > 0">
                <div class="relation-tags">
                  <a-tag 
                    v-for="(relation, index) in relatedEntities" 
                    :key="index" 
                    :color="getRelationTagColor(relation)"
                    class="relation-tag"
                  >
                    <span class="relation-indicator">
                      {{ relation.direction === 'outgoing' ? '→' : '←' }}
                    </span>
                    <span class="relation-text">
                      {{ relation.type }} · {{ relation.entityName }}
                    </span>
                    <a-dropdown placement="bottomRight" trigger="hover" :mouseEnterDelay="0.3">
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="title" disabled>
                            <span class="dropdown-title">修改关系类型</span>
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item 
                            v-for="option in relationTypeOptions" 
                            :key="option.value"
                            @click="changeRelationType(relation, index, option.value)"
                          >
                            <a-tag :color="relation.type === option.value ? 'blue' : ''">
                              {{ option.label }}
                            </a-tag>
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="delete" danger @click="deleteRelation(relation, index)">
                            <span class="delete-text">删除关系</span>
                          </a-menu-item>
                        </a-menu>
                      </template>
                      <span class="relation-menu-trigger">
                        <i class="fas fa-ellipsis-v"></i>
                      </span>
                    </a-dropdown>
                  </a-tag>
                </div>
              </template>
              <a-empty v-else description="暂无关联关系" class="empty-relations" />
            </div>
            
            <div class="form-label1">删除实体</div>
            <a-alert
                  type="warning"
                  show-icon
                  message="删除该实体会删除所有相关关系以及删除实体下所有次级实体"
                />
            <div class="delete-button-container">
              <a-button size="small" danger @click="deleteEntity">删除实体</a-button>
            </div>
          </template>
          <template v-else-if="selectedItem?.type === 'edge'">
            <!-- 关系编辑表单 -->
            <div class="edit-section">
              <div class="section-title">基本信息</div>
              <div class="form-item">
                <div class="form-label">关系类型</div>
                <a-select
                  v-model:value="selectedItem.relationType"
                  style="width: 100%"
                  :options="relationTypeOptions"
                />
              </div>
            </div>
            
            <div class="edit-section">
              <div class="section-title">高级信息</div>
              <div class="form-item">
                <div class="form-label">关系描述</div>
                <a-textarea
                  v-model:value="selectedItem.description"
                  placeholder="请输入关系描述"
                  :rows="3"
                />
              </div>
            </div>
          </template>
          <div class="form-actions">
            <a-button type="primary" @click="saveChanges">保存</a-button>
            <a-button @click="closeEditCard">取消</a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount, defineExpose, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { GraphChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GraphChart,
  CanvasRenderer
]);

// 定义组件属性
const props = defineProps({
  document: {
    type: Object,
    required: true
  }
});

// 图表容器引用和实例
const graphContainer = ref(null);
let chartInstance = null;

// 卡片状态
const isEntityTypeCardCollapsed = ref(false);
const isDataCardCollapsed = ref(false);

// 选中的实体类型
const selectedEntityTypes = ref([]);

// 关系类型选项
const relationTypeOptions = [
  { value: '隐式依赖', label: '隐式依赖' },
  { value: '显式依赖', label: '显式依赖' }
];

// 选中的实体数据
const selectedEntities = ref([]);
// 编辑前的实体数据备份
const originalEntities = ref([]);

// 选中的项目
const selectedItem = ref(null);

// 关联实体列表
const relatedEntities = ref([]);

// 表格列定义
const columns = [
  {
    dataIndex: 'label',
    key: 'label',
    width: '100px',
    ellipsis: true
  },
  {
    dataIndex: 'value',
    key: 'value',
    ellipsis: true
  }
];

// 搜索文本
const searchText = ref('');

// 定义格式化的数据
const graphData = ref({
  nodes: [
    {
      "id": "api_put",
      "name": "【修改用户信息】PUT /api/v1/user",
      "category": 0,
      "type": "接口",
      "fields": {
        "ID": "API_PUT",
        "METHOD": "PUT",
        "SUMMARY": "修改用户信息",
        "URL": "/api/v1/user"
      }
    },
    {
      "id": "param_put_body",
      "name": "body (修改用户信息)",
      "category": 1,
      "type": "参数",
      "fields": {
        "id": "用户名: 用户名",
        "username": "用户名称: 用户名称",
        "userdesc": "用户描述: 用户描述",
        "role": "用户权限: 用户权限",
        "allownets": "管理IP/掩码: 管理IP/掩码",
        "cyclepwdstate": "密码检查状态: 密码检查状态",
        "daycount": "修改密码周期: 修改密码周期",
        "locktime": "锁定时间: 锁定时间",
        "sessions": "会话数: 会话数1-10，默认为10"
      }
    },
    {
      "id": "api_post",
      "name": "【创建用户】POST /api/v1/user",
      "category": 0,
      "type": "接口",
      "fields": {
        "ID": "API_POST",
        "METHOD": "POST",
        "SUMMARY": "创建用户",
        "URL": "/api/v1/user"
      }
    },
    {
      "id": "param_post_body",
      "name": "body (创建用户)",
      "category": 1,
      "type": "参数",
      "fields": {
        "username": "用户名: 用户名支持输入1-63个字符 由中文/⼤⼩写字母/数字/点号/下划线构成",
        "passwd": "用户密码: 用户密码支持输入8-63个字符 由⼤写字母/⼩写字母/数字/指定字符（_!@#$%^&*`~()-.+=）构成，必须同时包含以上字符类型 密码不能和用户名/登录名相同或相反",
        "userdesc": "用户描述: 用户描述，0-127",
        "role": "角色权限: 角色权限",
        "group": "所属组: 所属组",
        "autht": "认证方式: 认证方式",
        "allownets": "管理IP/掩码: 管理IP/掩码最大允许输入10个子网地址，支持输入IPv4格式子网地址",
        "cyclepwdstate": "密码检查状态: 密码检查状态",
        "daycount": "修改密码周期: 修改密码周期",
        "lockstate": "锁定状态: 锁定状态",
        "sessions": "会话数: 会话数，1-10，默认为10"
      }
    },
    {
      "id": "api_delete",
      "name": "【删除某个用户】DELETE /api/v1/user",
      "category": 0,
      "type": "接口",
      "fields": {
        "ID": "API_DELETE",
        "METHOD": "DELETE",
        "SUMMARY": "删除某个用户",
        "URL": "/api/v1/user"
      }
    },
    {
      "id": "param_delete_query_id",
      "name": "params (删除用户)",
      "category": 1,
      "type": "参数",
      "fields": {
        "id": "字段含义为用户名称"
      }
    },
    {
      "id": "api_get",
      "name": "【获取所有用户】GET /api/v1/user",
      "category": 0,
      "type": "接口",
      "fields": {
        "ID": "API_GET",
        "METHOD": "GET",
        "SUMMARY": "获取所有用户",
        "URL": "/api/v1/user"
      }
    },
    {
      "id": "param_get_body",
      "name": "body (获取用户)",
      "category": 1,
      "type": "参数",
      "fields": {
        "loginTime": "登录时间: 登录时间",
        "username": "用户名: 用户名",
        "userdesc": "用户描述: 用户描述",
        "role": "权限: 权限",
        "group": "所属组: 所属组",
        "autht": "认证方式: 认证方式",
        "cert": "证书路径: 证书路径",
        "status": "状态: 状态",
        "allownets": "允许访问的源IP地址段: 允许访问的源IP地址段",
        "enable": "是否开启: 是否开启"
      }
    }
  ],
  links: [
    {
      "source": "api_put",
      "target": "param_put_body",
      "name": "参数",
      "description": "请求体参数"
    },
    {
      "source": "api_post",
      "target": "param_post_body",
      "name": "参数",
      "description": "请求体参数"
    },
    {
      "source": "api_delete",
      "target": "param_delete_query_id",
      "name": "参数",
      "description": "查询参数"
    },
    {
      "source": "api_get",
      "target": "param_get_body",
      "name": "参数",
      "description": "响应体参数"
    },
    {
      "source": "api_put",
      "target": "api_post",
      "name": "显式依赖",
      "description": "参数传递型依赖"
    }
    ,
    {
      "source": "api_delete",
      "target": "api_post",
      "name": "显式依赖",
      "description": "参数传递型依赖"
    }
  ],
  categories: [
    { name: '接口' },
    { name: '参数' }
  ]
});

// 初始化图谱
const initGraph = () => {
  if (!graphContainer.value) return;
  
  // 销毁旧实例
  if (chartInstance) {
    chartInstance.off('click');
    chartInstance.dispose();
  }
  
  // 创建新实例
  chartInstance = echarts.init(graphContainer.value);
  
  // 配置项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      data: graphData.value.categories.map(c => c.name),
      top: 'bottom'
    },
    animationDuration: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [{
      name: '知识图谱',
      type: 'graph',
      layout: 'force',
      data: graphData.value.nodes,
      links: graphData.value.links,
      categories: graphData.value.categories,
      roam: true,
      draggable: true,
      focusNodeAdjacency: true,
      label: {
        show: true,
        position: 'right',
        formatter: (params) => {
          if (params.data.type === '接口') {
            return params.data.fields?.SUMMARY || params.data.name;
          }
          return params.data.name;
        }
      },
      force: {
        repulsion: 100,
        edgeLength: 100,
        gravity: 0.1,
        friction: 0.6,
        initLayout: 'circular'
      },
      lineStyle: {
        color: 'source',
        curveness: 0.3,
        width: 2
      },
      emphasis: {
        focus: 'adjacency',
        lineStyle: {
          width: 3
        },
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold',
          formatter: (params) => {
            if (params.data.type === '接口') {
              return params.data.fields?.SUMMARY || params.data.name;
            }
            return params.data.name;
          }
        }
      },
      itemStyle: {
        borderWidth: 2,
        borderColor: '#fff'
      },
      symbolSize: 40,
      cursor: 'move'
    }]
  };
  
  // 设置配置项
  chartInstance.setOption(option);
  
  // 添加点击事件
  chartInstance.on('click', (params) => {
    if (params.dataType === 'node') {
      // 检查节点是否被筛选出来
      const nodeOpacity = params.data.itemStyle?.opacity || 1;
      if (nodeOpacity < 0.5) {
        // 如果节点透明度低于0.5，说明被筛选掉了，不处理点击
        return;
      }

      // 点击节点
      selectedItem.value = {
        type: 'node',
        id: params.data.id,
        name: params.data.name,
        category: params.data.category,
        description: params.data.description || '',
        nodeData: params.data // 存储完整的节点数据
      };
      
      // 查找相关联的实体和关系
      const relatedLinksAndNodes = findRelatedEntities(params.data.id);
      relatedEntities.value = relatedLinksAndNodes;
      
      // 更新选中的实体数据
      updateSelectedEntities([{
        id: params.data.id,
        name: params.data.name,
        type: params.data.type,
        fields: params.data.fields || {}
      }]);
      
      // 展开数据卡片
      isDataCardCollapsed.value = false;
      
      // 只显示相关节点和边
      const option = chartInstance.getOption();
      
      // 找出所有相关的边
      const relatedLinks = graphData.value.links.filter(link => 
        link.source === params.data.id || link.target === params.data.id
      );
      
      // 找出所有相关的节点ID
      const relatedNodeIds = new Set();
      relatedNodeIds.add(params.data.id);
      relatedLinks.forEach(link => {
        relatedNodeIds.add(link.source);
        relatedNodeIds.add(link.target);
      });
      
      // 更新节点和边的显示状态
      option.series[0].data = graphData.value.nodes.map(node => ({
        ...node,
        itemStyle: {
          opacity: relatedNodeIds.has(node.id) ? 1 : 0.1
        }
      }));
      
      option.series[0].links = graphData.value.links.map(link => ({
        ...link,
        lineStyle: {
          opacity: relatedNodeIds.has(link.source) && relatedNodeIds.has(link.target) ? 1 : 0.1
        }
      }));
      
      chartInstance.setOption(option);
    } else if (params.dataType === 'edge') {
      // 图表上点击边时
      
      // 更新选中的边数据
      selectedItem.value = {
        type: 'edge',
        source: params.data.source,
        target: params.data.target,
        relationType: params.data.name || '',
        description: params.data.description || ''
      };
      
      // 查找边关联的源节点和目标节点
      const sourceNode = graphData.value.nodes.find(n => n.id === params.data.source);
      const targetNode = graphData.value.nodes.find(n => n.id === params.data.target);
      
      // 更新选中的实体数据（不关闭右侧编辑卡片）
      updateSelectedEntities([
        {
          id: sourceNode.id,
          name: sourceNode.name,
          type: sourceNode.type,
          fields: sourceNode.fields || {}
        },
        {
          id: targetNode.id,
          name: targetNode.name,
          type: targetNode.type,
          fields: targetNode.fields || {}
        }
      ]);
      
      // 展开数据卡片
      isDataCardCollapsed.value = false;
      
      // 只显示相关的节点和边
      const option = chartInstance.getOption();
      const sourceId = params.data.source;
      const targetId = params.data.target;
      
      // 更新节点和边的显示状态
      option.series[0].data = graphData.value.nodes.map(node => ({
        ...node,
        itemStyle: {
          opacity: node.id === sourceId || node.id === targetId ? 1 : 0.1
        }
      }));
      
      option.series[0].links = graphData.value.links.map(link => ({
        ...link,
        lineStyle: {
          opacity: (link.source === sourceId && link.target === targetId) || 
                  (link.source === targetId && link.target === sourceId) ? 1 : 0.1
        }
      }));
      
      chartInstance.setOption(option);
    }
  });
  
  // 添加空白处点击事件
  chartInstance.getZr().on('click', (params) => {
    if (!params.target) {
      // 点击空白处
      selectedItem.value = null;
      selectedEntities.value = [];
      
      // 显示所有节点和边
      const option = chartInstance.getOption();
      option.series[0].data = graphData.value.nodes.map(node => ({
        ...node,
        itemStyle: {
          opacity: 1
        }
      }));
      
      option.series[0].links = graphData.value.links.map(link => ({
        ...link,
        lineStyle: {
          opacity: 1
        }
      }));
      
      chartInstance.setOption(option);
    }
  });
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 放大
const zoomIn = () => {
  if (chartInstance) {
    const option = chartInstance.getOption();
    const zoom = option.series[0].zoom || 1;
    option.series[0].zoom = zoom * 1.2;
    chartInstance.setOption(option);
  }
};

// 缩小
const zoomOut = () => {
  if (chartInstance) {
    const option = chartInstance.getOption();
    const zoom = option.series[0].zoom || 1;
    option.series[0].zoom = zoom / 1.2;
    chartInstance.setOption(option);
  }
};

// 重置视图
const resetView = () => {
  if (chartInstance) {
    const option = chartInstance.getOption();
    option.series[0].zoom = 1;
    chartInstance.setOption(option);
  }
};

// 关闭编辑卡片
const closeEditCard = () => {
  if (selectedItem.value) {
    selectedItem.value = null;
    relatedEntities.value = []; // 清空关联实体
    
    // 显示所有节点和边
    if (chartInstance) {
      const option = chartInstance.getOption();
      const { nodes, links } = generateGraphData();
      
      option.series[0].data = nodes.map(node => ({
        ...node,
        itemStyle: {
          opacity: 1
        }
      }));
      
      option.series[0].links = links.map(link => ({
        ...link,
        lineStyle: {
          opacity: 1
        }
      }));
      
      chartInstance.setOption(option);
    }
  }
};

// 保存更改
const saveChanges = () => {
  if (!selectedItem.value) return;
  
  // TODO: 实现保存逻辑
  console.log('保存更改:', selectedItem.value);
  
  // 更新图谱数据
  const option = chartInstance.getOption();
  if (selectedItem.value.type === 'node') {
    // 更新节点
    const nodeIndex = option.series[0].data.findIndex(node => node.id === selectedItem.value.id);
    if (nodeIndex !== -1) {
      option.series[0].data[nodeIndex] = {
        ...option.series[0].data[nodeIndex],
        name: selectedItem.value.name,
        category: selectedItem.value.category,
        description: selectedItem.value.description || ''
      };
    }
  } else if (selectedItem.value.type === 'edge') {
    // 更新边
    const edgeIndex = option.series[0].links.findIndex(link => 
      link.source === selectedItem.value.source && 
      link.target === selectedItem.value.target
    );
    if (edgeIndex !== -1) {
      option.series[0].links[edgeIndex] = {
        ...option.series[0].links[edgeIndex],
        name: selectedItem.value.relationType || '',
        description: selectedItem.value.description || ''
      };
    }
  }
  
  chartInstance.setOption(option);
  closeEditCard();
};

// 刷新图谱数据
const refreshGraphData = () => {
  console.log('刷新图谱数据');
  // 清空选中状态
  selectedItem.value = null;
  selectedEntities.value = [];
  searchText.value = '';
  
  // 重置图谱数据
  graphData.value = null;
  
  // 重新生成数据并初始化图谱
  initGraph();
};

// 监听文档变化
watch(() => props.document, () => {
  // 不再自动初始化图谱，仅在第一次或明确刷新时初始化
  // initGraph();
  
  // 如果图谱还没有初始化，才初始化
  if (!chartInstance) {
    initGraph();
  }
}, { deep: true });

// 监听实体类型选择变化
watch(selectedEntityTypes, (newTypes) => {
  if (chartInstance) {
    const option = chartInstance.getOption();
    const { nodes, links } = generateGraphData();
    
    // 更新节点显示状态
    option.series[0].data = nodes.map(node => ({
      ...node,
      itemStyle: {
        opacity: newTypes.length === 0 || newTypes.includes(node.type) ? 1 : 0.1
      }
    }));
    
    // 更新边的显示状态
    option.series[0].links = links.map(link => {
      const sourceNode = nodes.find(n => n.id === link.source);
      const targetNode = nodes.find(n => n.id === link.target);
      const shouldShow = newTypes.length === 0 || 
                        (newTypes.includes(sourceNode.type) && newTypes.includes(targetNode.type));
      
      return {
        ...link,
        lineStyle: {
          opacity: shouldShow ? 1 : 0.1
        }
      };
    });
    
    chartInstance.setOption(option);
  }
}, { deep: true });

// 组件挂载时初始化
onMounted(() => {
  initGraph();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});

// 暴露方法给父组件
defineExpose({
  refreshGraphData
});

// 设置实体为已编辑状态
const setEntityEdited = (entity, isEdited) => {
  entity.isEdited = isEdited;
};

// 保存实体字段修改
const saveEntityChanges = (entity, index) => {
  // 更新图谱中的节点数据
  if (chartInstance) {
    const option = chartInstance.getOption();
    const nodeIndex = option.series[0].data.findIndex(node => 
      node.id === entity.id || node.name === entity.name
    );
    
    if (nodeIndex !== -1) {
      // 更新图谱节点的字段数据
      option.series[0].data[nodeIndex].fields = { ...entity.fields };
      chartInstance.setOption(option);
      
      // 更新成功后移除编辑状态
      entity.isEdited = false;
      
      // 更新原始备份
      if (originalEntities.value[index]) {
        originalEntities.value[index] = JSON.parse(JSON.stringify(entity));
      }
    }
  }
};

// 取消实体字段修改
const cancelEntityChanges = (entity, index) => {
  // 恢复原始数据
  if (originalEntities.value[index]) {
    Object.assign(entity, JSON.parse(JSON.stringify(originalEntities.value[index])));
  }
  entity.isEdited = false;
};

// 更新选中的实体数据和创建备份
const updateSelectedEntities = (entities) => {
  selectedEntities.value = entities.map(entity => ({
    ...entity,
    isEdited: false,
    editingField: null,
    originalValue: null
  }));
  
  // 创建深拷贝备份
  originalEntities.value = JSON.parse(JSON.stringify(selectedEntities.value));
};

// 开始编辑字段
const startEditField = (entity, fieldKey) => {
  entity.editingField = fieldKey;
  entity.originalValue = entity.fields[fieldKey];
  
  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    const inputEl = document.getElementById(`field-input-${entity.id}-${fieldKey}`);
    if (inputEl) {
      // 获取内部的真实input元素
      const inputDom = inputEl.querySelector('input');
      if (inputDom) {
        inputDom.focus();
      }
    }
  });
};

// 完成编辑字段
const finishEditField = (entity) => {
  // 检查值是否变化
  if (entity.originalValue !== entity.fields[entity.editingField]) {
    entity.isEdited = true;
  }
  entity.editingField = null;
};

// 查找与节点相关的实体和关系
const findRelatedEntities = (nodeId) => {
  if (!graphData.value) return [];
  
  const { nodes, links } = graphData.value;
  const relatedItems = [];
  const processedRelations = new Set(); // 用于记录已处理过的关系，避免重复
  
  // 找出所有相关的边
  links.forEach(link => {
    let isSource = false;
    let isTarget = false;
    
    // 比较字符串或数字类型的ID
    if (typeof link.source === 'object' && link.source !== null) {
      isSource = link.source.id === nodeId;
    } else {
      isSource = link.source === nodeId;
    }
    
    if (typeof link.target === 'object' && link.target !== null) {
      isTarget = link.target.id === nodeId;
    } else {
      isTarget = link.target === nodeId;
    }
    
    if (isSource || isTarget) {
      // 获取关联节点ID
      let relatedNodeId;
      if (isSource) {
        relatedNodeId = typeof link.target === 'object' ? link.target.id : link.target;
      } else {
        relatedNodeId = typeof link.source === 'object' ? link.source.id : link.source;
      }
      
      // 创建关系的唯一标识符，避免重复添加
      const relationKey = isSource 
        ? `${nodeId}->${relatedNodeId}-${link.name}`
        : `${relatedNodeId}->${nodeId}-${link.name}`;
        
      // 如果关系已经处理过，则跳过
      if (processedRelations.has(relationKey)) {
        return;
      }
      
      // 记录已处理的关系
      processedRelations.add(relationKey);
      
      // 查找关联节点
      const relatedNode = nodes.find(n => n.id === relatedNodeId);
      
      if (relatedNode) {
        relatedItems.push({
          direction: isSource ? 'outgoing' : 'incoming',
          type: link.name || '关联',
          entityId: relatedNodeId,
          entityName: relatedNode.name,
          entityType: relatedNode.type || (relatedNode.category === 0 ? '接口' : '参数'),
          linkData: link, // 存储原始边数据
          relationKey // 添加唯一标识符
        });
      }
    }
  });
  
  return relatedItems;
};

// 获取关系标签颜色
const getRelationTagColor = (relation) => {
  // 基于目标实体的类型和关系方向返回不同颜色
  const entityType = relation.entityType;
  
  // 首先根据实体类型区分颜色
  if (entityType === '接口') {
    // 接口类型的实体
    if (relation.direction === 'outgoing') {
      // 向外的关系
      return relation.type.includes('显示依赖') ? '#1890ff' : '#52c41a'; // 蓝色表示显示依赖，绿色表示其他
    } else {
      // 向内的关系
      return relation.type.includes('显示依赖') ? '#722ed1' : '#faad14'; // 紫色表示显示依赖，黄色表示其他
    }
  } else if (entityType === '参数') {
    // 参数类型的实体
    if (relation.direction === 'outgoing') {
      // 向外的关系
      return relation.type.includes('显示依赖') ? '#13c2c2' : '#eb2f96'; // 青色表示显示依赖，粉色表示其他
    } else {
      // 向内的关系
      return relation.type.includes('显示依赖') ? '#fa541c' : '#2f54eb'; // 橙色表示显示依赖，深蓝表示其他
    }
  }
  
  // 默认颜色
  return relation.direction === 'outgoing' ? 'blue' : 'green';
};

// 删除实体
const deleteEntity = () => {
  if (!selectedItem.value || selectedItem.value.type !== 'node') return;
  
  const entityId = selectedItem.value.id;
  
  // 获取图表数据
  const option = chartInstance.getOption();
  
  // 找出所有相关的边
  const relatedLinks = graphData.value.links.filter(link => 
    link.source === entityId || link.target === entityId
  );
  
  // 找出所有下级实体
  const childEntityIds = new Set();
  // 递归查找下级实体
  const findChildEntities = (parentId) => {
    graphData.value.links.forEach(link => {
      if (link.source === parentId) {
        const childId = link.target;
        if (!childEntityIds.has(childId)) {
          childEntityIds.add(childId);
          findChildEntities(childId);
        }
      }
    });
  };
  
  // 开始递归查找
  findChildEntities(entityId);
  
  // 更新节点和边的数据
  const updatedNodes = graphData.value.nodes.filter(node => 
    node.id !== entityId && !childEntityIds.has(node.id)
  );
  
  const updatedLinks = graphData.value.links.filter(link => 
    link.source !== entityId && link.target !== entityId &&
    !childEntityIds.has(link.source) && !childEntityIds.has(link.target)
  );
  
  // 更新原始数据
  graphData.value.nodes = updatedNodes;
  graphData.value.links = updatedLinks;
  
  // 更新图表
  option.series[0].data = updatedNodes;
  option.series[0].links = updatedLinks;
  
  chartInstance.setOption(option);
  
  // 关闭编辑卡片
  closeEditCard();
};

// 修改关系类型
const changeRelationType = (relation, index, newType) => {
  if (relation.type === newType) return;
  
  // 获取原始链接数据
  const linkData = relation.linkData;
  if (!linkData) return;
  
  // 更新关系数据
  const { entityId, direction } = relation;
  const sourceId = direction === 'outgoing' ? selectedItem.value.id : entityId;
  const targetId = direction === 'outgoing' ? entityId : selectedItem.value.id;
  
  // 获取图表数据
  const option = chartInstance.getOption();
  
  // 查找并更新关系边
  const linkIndex = option.series[0].links.findIndex(link => {
    const linkSource = typeof link.source === 'object' ? link.source.id : link.source;
    const linkTarget = typeof link.target === 'object' ? link.target.id : link.target;
    return (linkSource === sourceId && linkTarget === targetId) || 
           (linkSource === targetId && linkTarget === sourceId);
  });
  
  if (linkIndex !== -1) {
    // 更新关系类型
    option.series[0].links[linkIndex].name = newType;
    
    // 更新本地关系数据
    relatedEntities.value[index].type = newType;
    
    // 更新原始数据
    if (graphData.value) {
      const originalLinkIndex = graphData.value.links.findIndex(link => {
        const linkSource = typeof link.source === 'object' ? link.source.id : link.source;
        const linkTarget = typeof link.target === 'object' ? link.target.id : link.target;
        return (linkSource === sourceId && linkTarget === targetId) || 
               (linkSource === targetId && linkTarget === sourceId);
      });
      
      if (originalLinkIndex !== -1) {
        graphData.value.links[originalLinkIndex].name = newType;
      }
    }
    
    // 更新图表
    chartInstance.setOption(option);
  }
};

// 删除关系
const deleteRelation = (relation, index) => {
  // 获取原始链接数据
  const linkData = relation.linkData;
  if (!linkData) return;
  
  // 获取关系数据
  const { entityId, direction } = relation;
  const sourceId = direction === 'outgoing' ? selectedItem.value.id : entityId;
  const targetId = direction === 'outgoing' ? entityId : selectedItem.value.id;
  
  // 获取图表数据
  const option = chartInstance.getOption();
  
  // 过滤掉要删除的关系边
  option.series[0].links = option.series[0].links.filter(link => {
    const linkSource = typeof link.source === 'object' ? link.source.id : link.source;
    const linkTarget = typeof link.target === 'object' ? link.target.id : link.target;
    return !(linkSource === sourceId && linkTarget === targetId) && 
           !(linkSource === targetId && linkTarget === sourceId);
  });
  
  // 更新原始数据
  if (graphData.value) {
    graphData.value.links = graphData.value.links.filter(link => {
      const linkSource = typeof link.source === 'object' ? link.source.id : link.source;
      const linkTarget = typeof link.target === 'object' ? link.target.id : link.target;
      return !(linkSource === sourceId && linkTarget === targetId) && 
             !(linkSource === targetId && linkTarget === sourceId);
    });
  }
  
  // 更新本地关系数据
  relatedEntities.value.splice(index, 1);
  
  // 更新图表
  chartInstance.setOption(option);
};
</script>

<style scoped>
.relation-map {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.graph-container {
  width: 100%;
  height: 100%;
}

.toolbar {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
}

.tool-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.toolbar button {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.toolbar button:hover {
  background-color: #f0f0f0;
}

.toolbar i {
  font-size: 14px;
  color: #595959;
}

.toolbar button:hover i {
  color: #1890ff;
}

/* 浮动卡片样式 */
.floating-cards {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.entity-type-card,
.data-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 280px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.entity-type-card:hover,
.data-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.card-title {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.card-content {
  padding: 12px 16px;
  background-color: #fff;
}

.filter-input {
  margin-bottom: 12px;
}

.filter-input :deep(.ant-input-search) {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.filter-input :deep(.ant-input-search:hover) {
  border-color: #d9d9d9;
}

.filter-input :deep(.ant-input-search:focus-within) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.filter-input :deep(.ant-input-search .ant-input) {
  border: none;
  background-color: transparent;
  padding: 4px 8px;
}

.filter-input :deep(.ant-input-search .ant-input:focus) {
  box-shadow: none;
}

.filter-input :deep(.ant-input-search-button) {
  background-color: transparent;
  border: none;
  color: #8c8c8c;
  transition: all 0.3s;
}

.filter-input :deep(.ant-input-search-button:hover) {
  color: #1890ff;
  background-color: transparent;
}

.entity-type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
  padding: 8px;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.entity-type-tag {
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #f0f0f0;
  background-color: #fff;
}

.entity-type-tag:hover {
  border-color: #91d5ff;
  color: #1890ff;
}

.entity-type-tag.ant-tag-blue {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.filter-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px dashed #f0f0f0;
}

.filter-actions button {
  min-width: 60px;
  height: 24px;
  font-size: 12px;
  padding: 0 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.filter-actions button:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
  cursor: not-allowed;
}

.filter-actions button:not(:disabled):hover {
  opacity: 0.8;
}

.data-list {
  max-height: 300px;
  overflow-y: auto;
}

.entity-item {
  padding: 8px;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: default;
}

.entity-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #f0f0f0;
}

.entity-name {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.entity-fields {
  margin-top: 8px;
}

.field-item {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.field-label {
  font-size: 12px;
  color: #8c8c8c;
  width: 80px;
  flex-shrink: 0;
  text-align: left;
  padding-right: 8px;
  padding-top: 4px;
}

.field-value {
  font-size: 12px;
  color: #262626;
  flex: 1;
  word-break: break-all;
  padding: 4px 0;
  text-align: left;
  line-height: 1.5;
}

.field-value.editable {
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed transparent;
  padding: 4px;
  border-radius: 4px;
}

.field-value.editable:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.field-input {
  font-size: 12px;
  height: 24px;
  flex: 1;
}

.field-input :deep(.ant-input) {
  font-size: 12px;
  padding: 0 8px;
}

.entity-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px dashed #f0f0f0;
}

.entity-actions button {
  height: 24px;
  font-size: 12px;
  padding: 0 8px;
}

.empty-data {
  padding: 32px 0;
}

.empty-data :deep(.ant-empty-image) {
  height: 80px;
  margin-bottom: 8px;
}

.empty-data :deep(.ant-empty-description) {
  color: #8c8c8c;
  font-size: 14px;
}

.card-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.entity-type-tag {
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  margin-bottom: 4px;
}

.entity-type-tag:hover {
  opacity: 0.8;
}

.entity-type-tag.ant-tag-blue {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.filter-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px dashed #f0f0f0;
}

.filter-actions button {
  min-width: 60px;
}

/* 关联关系样式 */
.related-entities {
  padding: 8px;
  border-radius: 4px;
  border: 1px dashed #e8e8e8;
  overflow-y: auto;
}

.relation-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.relation-tag {
  margin-right: 0;
  cursor: default;
  padding: 0 8px;
  border-radius: 4px;
  font-size: 12px;
  height: 24px;
  line-height: 22px;
  display: inline-flex;
  align-items: center;
  margin-bottom: 6px;
  transition: all 0.3s;
  max-width: 100%;
  position: relative;
}

.relation-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.relation-indicator {
  margin-right: 4px;
  font-size: 14px;
  font-weight: bold;
}

.relation-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-relations {
  padding: 12px 0;
}

.empty-relations :deep(.ant-empty-image) {
  height: 36px;
  margin-bottom: 4px;
}

.empty-relations :deep(.ant-empty-description) {
  color: #bfbfbf;
  font-size: 12px;
}

/* 右侧编辑卡片样式 */
.edit-card {
  position: absolute;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: right 0.3s ease;
  z-index: 10;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

.edit-card.show {
  right: 0;
}

.edit-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.edit-card .card-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fafafa;
}

.edit-card .card-title {
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

.edit-card .card-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #fff;
  position: relative;
  padding-bottom: 80px;
}

.edit-section {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 8px;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #e8e8e8;
}

.form-item {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-item:hover {
  border-color: #d9d9d9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-label {
  font-size: 14px;
  color: #262626;
  margin-bottom: 8px;
  text-align: left;
  font-weight: 500;
}

.form-label1 {
  font-size: 14px;
  color: #262626;
  margin-bottom: 8px;
  margin-top: 16px;
  text-align: left;
  font-weight: 500;
}

.form-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px;
  background-color: transparent;
  border: none;
  box-shadow: none;
}

/* 压缩效果 */
.graph-container.compressed {
  margin-right: 432px;
  transition: margin-right 0.3s ease;
}

.toolbar.compressed {
  right: 448px;
  transition: right 0.3s ease;
}

.entity-fields {
  margin-top: 8px;
}

.field-item {
  display: flex;
  margin-bottom: 4px;
}

.field-label {
  font-size: 12px;
  color: #8c8c8c;
  width: 80px;
  flex-shrink: 0;
}

.field-value {
  font-size: 12px;
  color: #262626;
  flex: 1;
  word-break: break-all;
  padding: 4px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.field-value.editable {
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed transparent;
}

.field-value.editable:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.empty-data {
  padding: 32px 0;
}

.empty-data :deep(.ant-empty-image) {
  height: 80px;
  margin-bottom: 8px;
}

.empty-data :deep(.ant-empty-description) {
  color: #8c8c8c;
  font-size: 14px;
}

.card-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.entity-type-tag {
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  margin-bottom: 4px;
}

.entity-type-tag:hover {
  opacity: 0.8;
}

.entity-type-tag.ant-tag-blue {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.filter-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px dashed #f0f0f0;
}

.filter-actions button {
  min-width: 60px;
}

/* 关联关系样式 */
.related-entities {
  padding: 8px;
  border-radius: 4px;
  border: 1px dashed #e8e8e8;
  overflow-y: auto;
}

.relation-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.relation-tag {
  margin-right: 0;
  cursor: default;
  padding: 0 8px;
  border-radius: 4px;
  font-size: 12px;
  height: 24px;
  line-height: 22px;
  display: inline-flex;
  align-items: center;
  margin-bottom: 6px;
  transition: all 0.3s;
  max-width: 100%;
  position: relative;
}

.relation-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.relation-indicator {
  margin-right: 4px;
  font-size: 14px;
  font-weight: bold;
}

.relation-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-relations {
  padding: 12px 0;
}

.empty-relations :deep(.ant-empty-image) {
  height: 36px;
  margin-bottom: 4px;
}

.empty-relations :deep(.ant-empty-description) {
  color: #bfbfbf;
  font-size: 12px;
}

/* 危险区域样式 */
.danger-section {
  border-color: #ffccc7;
  background-color: #fff2f0;
}

.danger-title {
  color: #cf1322;
}

.delete-warning {
  padding: 12px;
  border-radius: 4px;
}

.delete-warning :deep(.ant-alert) {
  margin-bottom: 16px;
  border: none;
  background-color: transparent;
}

.delete-warning :deep(.ant-alert-message) {
  color: #cf1322;
  font-size: 12px;
}

.delete-actions {
  display: flex;
  justify-content: flex-end;
}

.delete-button-container {
  margin-top: 12px;
  display: flex;
  justify-content: flex-start;
}

.relation-menu-trigger {
  opacity: 0;
  margin-left: 4px;
  font-size: 10px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  transition: all 0.2s;
  color: rgba(0, 0, 0, 0.45);
}

.relation-tag:hover .relation-menu-trigger {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.06);
}

.relation-menu-trigger:hover {
  background-color: rgba(0, 0, 0, 0.1);
  color: rgba(0, 0, 0, 0.65);
}

.dropdown-title {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
}

.delete-text {
  color: #ff4d4f;
}
</style>
